﻿using System;
using System.IO;
using System.IO.Compression;
using Commands.Settings;

namespace Commands.TorrentDownloaders
{
    internal class FreeTorrentsDownloadDispatcher : TokenDispatcherBase
    {
        public FreeTorrentsDownloadDispatcher(ServiceSettings settings)
            : base(settings)
        {

        }

        protected override string DecodeResponseBytes(byte[] bytesLoginResponse)
        {
            var decompressed = _Decompress(bytesLoginResponse);
            return base.DecodeResponseBytes(decompressed);
        }

        /// <summary>
        /// Decompress bytes gzip array.
        /// </summary>
        private static byte[] _Decompress(byte[] gzip)
        {
            using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
            {
                const int size = 4096;
                byte[] buffer = new byte[size];
                using (MemoryStream memory = new MemoryStream())
                {
                    int count = 0;
                    do
                    {
                        count = stream.Read(buffer, 0, size);
                        if (count > 0)
                        {
                            memory.Write(buffer, 0, count);
                        }
                    }
                    while (count > 0);
                    return memory.ToArray();
                }
            }
        }

        protected override Uri DispatcherLoginPage
        {
            get
            {
                return new Uri(@"http://login.free-torrents.org/forum/login.php");
            }
        }

        protected override string DOWNLOAD_LINK_REGEXP
        {
            get 
            {
                return "\"(?<download_link>http\\://dl\\.free-torrents\\.org/forum/dl\\.php\\?id=\\d\\d+)\"";
            }
        }

        protected override string CHECK_TRACKER_REGEXP
        {
            get 
            {
                return @"http\://free-torrents\.org/forum/viewtopic\.php\?t=\d+";
            }
        }
    }
}
